#!/usr/bin/env python3
"""
命令行文本计数统计程序
Author: 黄备煊
Version: v0.3 - 扩展功能
Date: 2025/10/28
"""

import re
import sys
import argparse
from pathlib import Path

class TextCounter:
    def __init__(self, filename):
        self.filename = filename
        self.content = ""
        
    def read_file(self):
        """读取文件内容"""
        try:
            # 使用二进制模式读取，自动处理编码
            with open(self.filename, 'rb') as f:
                raw_content = f.read()
            
            # 尝试不同的编码
            try:
                self.content = raw_content.decode('utf-8')
            except UnicodeDecodeError:
                try:
                    self.content = raw_content.decode('utf-16')
                except UnicodeDecodeError:
                    self.content = raw_content.decode('gbk')
            return True
        except FileNotFoundError:
            print(f"错误：文件 '{self.filename}' 不存在")
            return False
        except Exception as e:
            print(f"错误：{e}")
            return False
    
    def count_chars(self):
        """统计字符数"""
        return len(self.content)
    
    def count_words(self):
        """统计单词数"""
        # 使用正则表达式匹配单词
        words = re.findall(r'[a-zA-Z]+', self.content)
        return len(words)
    
    def count_sentences(self):
        """统计句子数"""
        # 基于 . ! ? 分割句子
        sentences = re.split(r'[.!?]+', self.content)
        sentences = [s.strip() for s in sentences if s.strip()]
        return len(sentences)
    
    def count_lines(self):
        """统计行数"""
        return len(self.content.splitlines())
    
    def code_analysis(self):
        """代码分析：统计代码行、空行、注释行"""
        lines = self.content.splitlines()
        code_lines = 0
        blank_lines = 0
        comment_lines = 0
        
        for line in lines:
            stripped = line.strip()
            
            if not stripped:
                blank_lines += 1
            elif stripped.startswith('#') or stripped.startswith('//'):
                comment_lines += 1
            else:
                code_lines += 1
                
        return {
            'total_lines': len(lines),
            'code_lines': code_lines,
            'blank_lines': blank_lines,
            'comment_lines': comment_lines
        }

def main():
    parser = argparse.ArgumentParser(description='文本统计工具')
    parser.add_argument('file', help='要统计的文件')
    parser.add_argument('-c', '--chars', action='store_true', help='统计字符数')
    parser.add_argument('-w', '--words', action='store_true', help='统计单词数')
    parser.add_argument('-s', '--sentences', action='store_true', help='统计句子数')
    parser.add_argument('-l', '--lines', action='store_true', help='统计行数')
    parser.add_argument('-a', '--all', action='store_true', help='显示所有统计')
    parser.add_argument('--code', action='store_true', help='代码分析')
    
    args = parser.parse_args()
    
    # 检查文件是否存在
    if not Path(args.file).exists():
        print(f"错误：文件 '{args.file}' 不存在")
        return
    
    counter = TextCounter(args.file)
    if not counter.read_file():
        return
    
    print(f"文件: {args.file}")
    print("-" * 30)
    
    # 根据参数显示统计结果
    if args.chars or args.all:
        print(f"字符数: {counter.count_chars()}")
    
    if args.words or args.all:
        print(f"单词数: {counter.count_words()}")
    
    if args.sentences or args.all:
        print(f"句子数: {counter.count_sentences()}")
    
    if args.lines or args.all:
        print(f"行数: {counter.count_lines()}")
    
    if args.code:
        stats = counter.code_analysis()
        print(f"总行数: {stats['total_lines']}")
        print(f"代码行: {stats['code_lines']}")
        print(f"空行: {stats['blank_lines']}")
        print(f"注释行: {stats['comment_lines']}")
    
    # 如果没有指定任何参数，默认显示基本信息
    if not any([args.chars, args.words, args.sentences, args.lines, args.all, args.code]):
        print(f"字符数: {counter.count_chars()}")
        print(f"单词数: {counter.count_words()}")
        print(f"句子数: {counter.count_sentences()}")
        print(f"行数: {counter.count_lines()}")

if __name__ == '__main__':
    main()